<script setup name="leftViews">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
	ternaryDatabase,
	binaryDatabase,
	elementOptions,
	validators,
	getAllElementsBinary,
	getAllElementsTernary,
	getSecondElementsBinaryUniversal,
	getSecondElementsTernaryUniversal,
	getThirdElementsTernaryUniversal,
} from '../utils/config.js'

const props = defineProps({
	isLoading: Boolean,
	type: String, // 'binary' 或 'ternary'
})

const emit = defineEmits(['on-submit'])

const formRef = ref(null)

// 根据类型决定使用二元还是三元的表单字段
const isBinary = computed(() => props.type === 'binary')

// 表单数据
const form = ref({
	// 通用字段
	firstElement: '',
	secondElement: '',
	thirdElement: '', // 仅三元使用
	pressure: 101325,

	// 二元相图字段
	tmin: 300,
	tmax: 1000,
	tstep: 10,
	xmin: 0,
	xmax: 1,
	xstep: 0.02,

	// 三元相图字段
	temperature: 800, // 三元只有一个温度值
	xAxisElement: '', // X轴元素选择
	yAxisElement: '', // Y轴元素选择
	fxmin: 0,
	fxmax: 1,
	fxstep: 0.02,
	sxmin: 0,
	sxmax: 1,
	sxstep: 0.02,
})

// 计算属性 - 当前TDB文件
const currentTdbFile = computed(() => {
	if (isBinary.value) {
		if (!form.value.firstElement || !form.value.secondElement) return ''
		const matched = binaryDatabase.getMatchedCombination([
			form.value.firstElement,
			form.value.secondElement,
		])
		return matched?.dbFile || ''
	} else {
		if (
			!form.value.firstElement ||
			!form.value.secondElement ||
			!form.value.thirdElement
		)
			return ''
		const matched = ternaryDatabase.getMatchedConfiguration([
			form.value.firstElement,
			form.value.secondElement,
			form.value.thirdElement,
		])
		return matched?.dbFile || ''
	}
})

// 验证规则
const validationRules = computed(() => {
	const baseRules = {
		firstElement: [validators.required('请选择第一个元素')],
		secondElement: [validators.required('请选择第二个元素')],
		pressure: [validators.positiveNumber('压强必须大于等于0')],
	}

	if (isBinary.value) {
		return {
			...baseRules,
			tmin: [validators.positiveNumber('最小温度必须大于等于0')],
			tmax: [validators.positiveNumber('最大温度必须大于等于0')],
			tstep: [validators.positiveStep('步长必须大于0')],
			xmin: [validators.range01('成分值必须在0到1之间')],
			xmax: [validators.range01('成分值必须在0到1之间')],
			xstep: [validators.step01('步长必须大于0且小于等于1')],
		}
	} else {
		return {
			...baseRules,
			thirdElement: [validators.required('请选择第三个元素')],
			xAxisElement: [validators.required('请选择X轴元素')],
			yAxisElement: [validators.required('请选择Y轴元素')],
			temperature: [validators.positiveNumber('温度必须大于等于0')],
			fxmin: [validators.range01('成分值必须在0到1之间')],
			fxmax: [validators.range01('成分值必须在0到1之间')],
			fxstep: [validators.step01('步长必须大于0且小于等于1')],
			sxmin: [validators.range01('成分值必须在0到1之间')],
			sxmax: [validators.range01('成分值必须在0到1之间')],
			sxstep: [validators.step01('步长必须大于0且小于等于1')],
		}
	}
})

// 计算属性 - 可选元素
const allElements = computed(() =>
	isBinary.value ? getAllElementsBinary() : getAllElementsTernary()
)
const availableSecondElements = computed(() =>
	isBinary.value
		? getSecondElementsBinaryUniversal(form.value.firstElement)
		: getSecondElementsTernaryUniversal(form.value.firstElement)
)
const availableThirdElements = computed(() =>
	getThirdElementsTernaryUniversal(
		form.value.firstElement,
		form.value.secondElement
	)
)

// 三元相图可选元素列表（用于X轴Y轴选择）
const ternaryElements = computed(() => {
	if (isBinary.value) return []
	if (
		!form.value.firstElement ||
		!form.value.secondElement ||
		!form.value.thirdElement
	)
		return []
	return [
		form.value.firstElement,
		form.value.secondElement,
		form.value.thirdElement,
	]
})

// 可选X轴元素（排除已选择的Y轴元素）
const availableXAxisElements = computed(() => {
	if (isBinary.value) return []
	if (
		!form.value.firstElement ||
		!form.value.secondElement ||
		!form.value.thirdElement
	)
		return []
	return ternaryElements.value.filter(
		(element) => element !== form.value.yAxisElement
	)
})

// 可选Y轴元素（排除已选择的X轴元素）
const availableYAxisElements = computed(() => {
	if (isBinary.value) return []
	if (
		!form.value.firstElement ||
		!form.value.secondElement ||
		!form.value.thirdElement
	)
		return []
	return ternaryElements.value.filter(
		(element) => element !== form.value.xAxisElement
	)
})

// 元素选项
const elementOptions_computed = computed(() => {
	return isBinary.value ? elementOptions.binary : elementOptions.ternary
})

// 方法
const handleFirstElementChange = () => {
	form.value.secondElement = ''
	if (!isBinary.value) {
		form.value.thirdElement = ''
	}
}

const handleSecondElementChange = () => {
	if (!isBinary.value) {
		form.value.thirdElement = ''
		form.value.xAxisElement = ''
		form.value.yAxisElement = ''
	}
}

// 处理第三个元素变化
const handleThirdElementChange = () => {
	if (!isBinary.value) {
		form.value.xAxisElement = ''
		form.value.yAxisElement = ''
	}
}

const resetForm = () => formRef.value?.resetFields()

const submitForm = async () => {
	if (!formRef.value) return
	try {
		await formRef.value.validate()

		let submitData = {}

		if (isBinary.value) {
			// 二元相图参数格式
			submitData = {
				elements: [form.value.firstElement, form.value.secondElement].join(','),
				tdb: currentTdbFile.value,
				pressure: form.value.pressure,
				tmin: form.value.tmin,
				tmax: form.value.tmax,
				tstep: form.value.tstep,
				xmin: form.value.xmin,
				xmax: form.value.xmax,
				xstep: form.value.xstep,
			}
		} else {
			// 三元相图参数格式
			submitData = {
				elements: [
					form.value.firstElement,
					form.value.secondElement,
					form.value.thirdElement,
				].join(','),
				tdb: currentTdbFile.value,
				pressure: form.value.pressure,
				temp: form.value.temperature,
				first: form.value.xAxisElement,
				second: form.value.yAxisElement,
				fxmin: form.value.fxmin,
				fxmax: form.value.fxmax,
				fxstep: form.value.fxstep,
				sxmin: form.value.sxmin,
				sxmax: form.value.sxmax,
				sxstep: form.value.sxstep,
			}
		}

		emit('on-submit', { ...submitData, type: props.type, model: 'phase' })
	} catch (error) {
		ElMessage.error('表单验证失败，请检查输入！')
	}
}
</script>

<template>
	<div class="left-middle">
		<el-form
			ref="formRef"
			:model="form"
			:rules="validationRules"
			label-width="0px"
			class="form"
		>
			<!-- 元素选择 -->
			<div class="section-row element-select-section-row">
				<div class="section-col">
					<div class="section-header">第一个元素</div>
					<el-form-item prop="firstElement">
						<el-select
							v-model="form.firstElement"
							class="section-select"
							@change="handleFirstElementChange"
							clearable
							placeholder="选择元素"
						>
							<el-option
								v-for="item in allElements"
								:key="item"
								:label="item"
								:value="item"
							/>
						</el-select>
					</el-form-item>
				</div>
				<div class="section-col">
					<div class="section-header">第二个元素</div>
					<el-form-item prop="secondElement">
						<el-select
							v-model="form.secondElement"
							class="section-select"
							@change="handleSecondElementChange"
							:disabled="!form.firstElement"
							clearable
							placeholder="选择元素"
						>
							<el-option
								v-for="item in availableSecondElements"
								:key="item"
								:label="item"
								:value="item"
							/>
						</el-select>
					</el-form-item>
				</div>
				<div v-if="!isBinary" class="section-col">
					<div class="section-header">第三个元素</div>
					<el-form-item prop="thirdElement">
						<el-select
							v-model="form.thirdElement"
							class="section-select"
							@change="handleThirdElementChange"
							:disabled="!form.firstElement || !form.secondElement"
							clearable
							placeholder="选择元素"
						>
							<el-option
								v-for="item in availableThirdElements"
								:key="item"
								:label="item"
								:value="item"
							/>
						</el-select>
					</el-form-item>
				</div>
				<div class="section-col">
					<div class="section-header">对应数据库</div>
					<el-form-item>
						<el-input
							v-model="currentTdbFile"
							class="section-input"
							readonly
							disabled
						/>
					</el-form-item>
				</div>
			</div>

			<hr />

			<!-- 压强 -->

			<!-- 二元相图：温度范围 -->
			<template v-if="isBinary">
				<div class="section-row">
					<div class="section-col">
						<div class="section-header">压强</div>
						<div class="section-title">压强值 (Pa)</div>
						<el-form-item prop="pressure">
							<el-input
								v-model="form.pressure"
								v-positive-number
								class="section-input"
								type="number"
								placeholder="101325"
							/>
						</el-form-item>
					</div>
				</div>

				<hr />
				<div class="section-row">
					<div class="section-col">
						<div class="section-header">温度范围 (K)</div>
					</div>
				</div>
				<div class="section-row three-squares">
					<div class="section-col">
						<div class="section-title">最小温度</div>
						<el-form-item prop="tmin">
							<el-input
								v-model="form.tmin"
								v-positive-number
								class="section-input"
								type="number"
								placeholder="300"
							/>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">最大温度</div>
						<el-form-item prop="tmax">
							<el-input
								v-model="form.tmax"
								v-positive-number
								class="section-input"
								type="number"
								placeholder="1000"
							/>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">步长</div>
						<el-form-item prop="tstep">
							<el-input
								v-model="form.tstep"
								v-positive-number
								class="section-input"
								type="number"
								placeholder="10"
							/>
						</el-form-item>
					</div>
				</div>

				<hr />

				<!-- 二元相图：成分范围 -->
				<div class="section-row">
					<div class="section-col">
						<div class="section-header">成分范围</div>
					</div>
				</div>
				<div class="section-row three-squares">
					<div class="section-col">
						<div class="section-title">最小成分</div>
						<el-form-item prop="xmin">
							<el-input
								v-model="form.xmin"
								v-positive-number="{ maxDecimals: 3, min: 0, max: 1 }"
								class="section-input"
								type="number"
								step="0.01"
								placeholder="0"
							/>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">最大成分</div>
						<el-form-item prop="xmax">
							<el-input
								v-model="form.xmax"
								v-positive-number="{ maxDecimals: 3, min: 0, max: 1 }"
								class="section-input"
								step="0.01"
								placeholder="1"
							/>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">步长</div>
						<el-form-item prop="xstep">
							<el-input
								v-model="form.xstep"
								v-positive-number
								class="section-input"
								placeholder="0.02"
							/>
						</el-form-item>
					</div>
				</div>
			</template>

			<!-- 三元相图：温度和压强 -->
			<template v-else>
				<div class="section-row element-select-section-row">
					<div class="section-col">
						<div class="section-header">压强</div>
						<div class="section-title">压强值 (Pa)</div>
						<el-form-item prop="pressure">
							<el-input
								v-model="form.pressure"
								v-positive-number
								class="section-input"
								type="number"
								placeholder="101325"
							/>
						</el-form-item>
					</div>

					<div class="section-col">
						<div class="section-header">温度</div>
						<div class="section-title">温度值 (K)</div>
						<el-form-item prop="temperature">
							<el-input
								v-model="form.temperature"
								v-positive-number
								class="section-input"
								type="number"
								placeholder="800"
							/>
						</el-form-item>
					</div>
				</div>

				<hr />

				<!-- 坐标轴元素选择 -->
				<div class="section-row">
					<div class="section-col">
						<div class="section-header">坐标轴元素选择</div>
					</div>
				</div>
				<div class="section-row three-squares">
					<div class="section-col">
						<div class="section-title">X轴元素</div>
						<el-form-item prop="xAxisElement">
							<el-select
								v-model="form.xAxisElement"
								class="section-select"
								:disabled="
									!form.firstElement ||
									!form.secondElement ||
									!form.thirdElement
								"
								clearable
								placeholder="选择X轴元素"
							>
								<el-option
									v-for="element in availableXAxisElements"
									:key="element"
									:label="element"
									:value="element"
								/>
							</el-select>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">Y轴元素</div>
						<el-form-item prop="yAxisElement">
							<el-select
								v-model="form.yAxisElement"
								class="section-select"
								:disabled="
									!form.firstElement ||
									!form.secondElement ||
									!form.thirdElement
								"
								clearable
								placeholder="选择Y轴元素"
							>
								<el-option
									v-for="element in availableYAxisElements"
									:key="element"
									:label="element"
									:value="element"
								/>
							</el-select>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">剩余元素</div>
						<el-form-item>
							<el-input
								:value="
									ternaryElements.filter(
										(el) => el !== form.xAxisElement && el !== form.yAxisElement
									)[0] || ''
								"
								class="section-input"
								readonly
								disabled
								placeholder="自动计算"
							/>
						</el-form-item>
					</div>
				</div>

				<hr />

				<!-- X轴元素成分范围 -->
				<div class="section-row">
					<div class="section-col">
						<div class="section-header">
							{{ form.xAxisElement || 'X轴元素' }}成分范围 (X轴)
						</div>
					</div>
				</div>
				<div class="section-row three-squares">
					<div class="section-col">
						<div class="section-title">最小值</div>
						<el-form-item prop="fxmin">
							<el-input
								v-model="form.fxmin"
								v-positive-number="{ maxDecimals: 3, min: 0, max: 1 }"
								class="section-input"
								type="number"
								step="0.01"
								placeholder="0"
							/>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">最大值</div>
						<el-form-item prop="fxmax">
							<el-input
								v-model="form.fxmax"
								v-positive-number="{ maxDecimals: 3, min: 0, max: 1 }"
								class="section-input"
								type="number"
								step="0.01"
								placeholder="1"
							/>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">步长</div>
						<el-form-item prop="fxstep">
							<el-input
								v-model="form.fxstep"
								v-positive-number
								class="section-input"
								placeholder="0.02"
							/>
						</el-form-item>
					</div>
				</div>

				<hr />

				<!-- Y轴元素成分范围 -->
				<div class="section-row">
					<div class="section-col">
						<div class="section-header">
							{{ form.yAxisElement || 'Y轴元素' }}成分范围 (Y轴)
						</div>
					</div>
				</div>
				<div class="section-row three-squares">
					<div class="section-col">
						<div class="section-title">最小值</div>
						<el-form-item prop="sxmin">
							<el-input
								v-model="form.sxmin"
								v-positive-number="{ maxDecimals: 3, min: 0, max: 1 }"
								class="section-input"
								type="number"
								step="0.01"
								placeholder="0"
							/>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">最大值</div>
						<el-form-item prop="sxmax">
							<el-input
								v-model="form.sxmax"
								v-positive-number="{ maxDecimals: 3, min: 0, max: 1 }"
								class="section-input"
								type="number"
								step="0.01"
								placeholder="1"
							/>
						</el-form-item>
					</div>
					<div class="section-col">
						<div class="section-title">步长</div>
						<el-form-item prop="sxstep">
							<el-input
								v-model="form.sxstep"
								v-positive-number
								class="section-input"
								placeholder="0.02"
							/>
						</el-form-item>
					</div>
				</div>
			</template>
		</el-form>
	</div>
	<div class="left-bottom">
		<el-button @click="resetForm">重置</el-button>
		<el-button color="black" :loading="props.isLoading" @click="submitForm">
			计算
		</el-button>
	</div>
</template>

<style scoped lang="scss">
@import url('./index.scss');
</style>
